package cn.snmp.mutual.org.opennms.protocols.snmp;

import cn.snmp.mutual.org.opennms.protocols.ip.IPv4Address;


import java.net.*;

public class SnmpIPAddress extends SnmpOctetString {
    static final long serialVersionUID = -4375760318106654741L;
    public static final byte ASNTYPE = 64;

    public SnmpIPAddress() {
        final byte[] tmp = {0, 0, 0, 0};
        this.setString(tmp);
    }

    public SnmpIPAddress(final byte[] data) {
        super(data);
    }

    public SnmpIPAddress(final SnmpIPAddress second) {
        super(second);
    }

    public SnmpIPAddress(final SnmpOctetString second) {
        super(second);
    }

    @Override
    public byte typeId() {
        return 64;
    }

    @Override
    public SnmpSyntax duplicate() {
        return new SnmpIPAddress(this);
    }

    @Override
    public Object clone() {
        return new SnmpIPAddress(this);
    }

    public IPv4Address convertToIpAddress() throws SnmpBadConversionException {
        final byte[] data = this.getString();
        if (data == null || data.length != 4) {
            throw new SnmpBadConversionException("Invalid IP Address Length");
        }
        return new IPv4Address(data);
    }

    @Override
    public String toString() {
        final byte[] data = this.getString();
        if (data != null && data.length > 4) {
            try {
                return InetAddress.getByAddress(this.getString()).getHostAddress();
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid IP Address");
            }
        }
        return IPv4Address.addressToString(data);
    }
}
